<template>
  <el-row v-loading="chartLoading" class="pie-row">
    <chart
      :option="commonRadarOption"
      ref="radarChart"
      auto-resize
      style="width: 100%; height: 100%"
    ></chart>
  </el-row>
</template>

<script>
import nt from '../../../../../network'
import parseApi from '../../../../utils/parseApi'

 import _ from 'lodash'
import mixinOption from '../../../../utils/mixinOption'

export default {
  name: 'custom-report-component-chart-radar',
  props: {
    api: {},
    method: {
      type: String,
      default: 'get',
    },
    dataKey: {},
    mainTitle: {},
    componentData: {},
    changeSize: {},
    changeData: {},
    interval: {},
    time: {},
    mixinParam: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      color: ['#419EFF', '#40E0D0', '#7FFFD4', '#00BFFF', '#FFDEAD'],
      chartLoading: false,
      isDataReady: false,
      score: 0,
      option: {
        tooltip: {
          trigger: 'item',
          axisPointer: {
            type: 'shadow',
          },
          position: function (point, params, dom, rect, size) {
            if (point[0] > size.viewSize[0] / 2) {
              return [point[0] - size.contentSize[0] - 30, '10%']
            } else {
              return [point[0] + 30, '10%']
            }
          },
        },
        title: {
          show: true,
          left: '',
          top: '',
          subtext: '', //`{a|评分}      {b|${appScoreObj.score}}`,
          subtextStyle: {
            align: 'center',
            left: '15%',
            rich: {
              verticalAlign: 'center',
              a: {
                fontFamily: 'PingFangSC-Medium',
                fontSize: '12',
                color: '',
                fontWeight: 'bold',
              },
              b: {
                fontFamily: 'PingFangSC-Medium',
                fontSize: '20',
                color: '',
              },
            },
          },
        },
        legend: {
          show: true,
          data: [],
          left: 'right',
          top: 'top',
          icon: 'circle',
          itemWidth: 9,
          itemHeight: 9,
          right: 20,
          y: 'top',
          tooltip: {
            show: true,
          },
          formatter: function (name) {
            if (!name) return ''
            if (name.length > 8) {
              name = name.slice(0, 8) + '...'
              return name
            } else {
              return name
            }
          },
        },
        radar: [
          {
            indicator: [],
            center: ['45%', '50%'],
            radius: '75%',
            splitArea: {
              areaStyle: {
                color: '#FFF',
              },
            },
            splitNumber: 4,
            splitLine: {
              lineStyle: {
                color: ['#E9E9E9'],
              },
            },
            axisLine: {
              lineStyle: {
                color: ['#E9E9E9'],
              },
            },
            name: {
              rich: {
                a: {
                  color: '#A3ADB6',
                  align: 'center',
                  fontFamily: 'PingFangSC-Regula',
                  fontSize: 12,
                  lineHeight: 20,
                },
                b: {
                  color: '#419EFF',
                  align: 'center',
                  fontFamily: 'PingFangSC-Regular',
                  fontSize: 14,
                },
              },
            },
          },
        ],
        series: [
          {
            type: 'radar',
            //拐点类型
            symbol: 'circle',
            tooltip: {
              trigger: 'item',
            },
            itemStyle: {
              normal: {
                areaStyle: { type: 'default', color: '#419EFF', opacity: 0.1 },
                lineStyle: { type: 'solid', color: '#419EFF', width: 1 },
                color: '#419EFF',
                shadowColor: '#419EFF',
              },
            },

            data: [],
          },
        ],
      },
      commonRadarOption: {},
    }
  },
  methods: {
    changeStyle: function () {
      let componentData = this.componentData
      let option = this.option
      let { title } = option
      title.show = componentData.title.subShow
      title.left = componentData.title.left
      title.top = componentData.title.top
      title.subtext = `{a|${componentData.title.subText}}      {b|${this.score}}`
      title.subtextStyle.rich.a.color = componentData.title.textColor
      title.subtextStyle.rich.b.color = componentData.title.valueColor
      for (let key in componentData.legend) {
        option.legend[key] = componentData.legend[key]
      }
      let color = componentData.color
      let series = option.series
      for (let i = 0; i < series.length; i++) {
        series[i].itemStyle.normal.areaStyle.color = color[i % 5]
        series[i].itemStyle.normal.lineStyle.color = color[i % 5]
        series[i].itemStyle.normal.color = color[i % 5]
        series[i].itemStyle.normal.shadowColor = color[i % 5]
      }
      option.radar[0].radius = componentData.radius + '%'
      let centerX = componentData.centerX + '%'
      let centerY = componentData.centerY + '%'
      let i = 0
      option.radar[0].name.formatter = (a, b) => {
        // value是每一项的平均值
        const value = option.series[0].data[0].value[i++]
        return `{b|${value}}\n{a|${a}}`
      }
      option.radar[0].center = [centerX, centerY]
      this.commonRadarOption = _.cloneDeep(option)
      if (componentData.code) {
        //给开发人员测试的，怕忘记删，生产环境就不打印了
        process.env.NODE_ENV === 'development' &&
          console.log(this.mainTitle + ' 混入前option', option)
        this.commonRadarOption = mixinOption(
          this.commonRadarOption,
          componentData.code
        )
        process.env.NODE_ENV === 'development' &&
          console.log(this.mainTitle + ' 混入后option', this.commonRadarOption)
      }
      if (this.$refs.radarChart) {
        this.$refs.radarChart.resize()
      }
    },
    getCommonData: function (callback, newApi) {
      this.chartLoading = true
      let parseData = (data) => {
        if (
          !data ||
          JSON.stringify(data) === '{}' ||
          !data.valueList ||
          !data.valueList.length
        ) {
          data = {
            indicator: [{ text: '', max: 0 }],
            valueList: [
              {
                name: '',
                data: [0],
                unit: '',
                totalScore: '',
              },
            ],
          }
        }
        this.chartLoading = false
        let option = this.option
        this.score = data.valueList[0].totalScore || 0
        let unit = ''
        option.radar[0].indicator = []
        data.indicator.forEach((idc) => {
          let indica = { text: idc.text, max: idc.max, color: '#A3ADB6' }
          option.radar[0].indicator.push(indica)
        })
        option.series = []
        option.legend.data = []
        let i = 0
        let color = this.color
        data.valueList.forEach((value) => {
          unit = value.unit
          let dataItem = { name: value.name, value: value.data }
          let series = {
            type: 'radar',
            //拐点类型
            symbol: 'circle',
            tooltip: {
              trigger: 'item',
            },
            itemStyle: {
              normal: {
                areaStyle: {
                  type: 'default',
                  color: color[i % 5],
                  opacity: 0.1,
                },
                lineStyle: { type: 'solid', color: color[i % 5], width: 1 },
                color: color[i % 5],
                shadowColor: color[i % 5],
              },
            },

            data: [dataItem],
          }
          option.legend.data.push(value.name)
          option.series.push(series)
          i++
        })

        option.tooltip.formatter = function (param) {
          let str = param.name + '<br/>'
          for (let i = 0; i < param.data.value.length; i++) {
            if (
              param.data.value[i] === ' ' ||
              (!param.data.value[i] && param.data.value[i] !== 0)
            ) {
              str =
                str +
                param.marker +
                option.radar[0].indicator[i].text +
                ':' +
                param.data.value[i] +
                '<br/>'
            } else {
              str =
                str +
                param.marker +
                option.radar[0].indicator[i].text +
                ':' +
                param.data.value[i] +
                (unit || '') +
                '<br/>'
            }
          }
          return str
        }
        if (!this.isDataReady) {
          this.isDataReady = true
          this.$emit( 'dataReady')
        }
      }
      if (!this.api || !this.api.reqUrl) {
        let data = {
          indicator: [
            { text: '外观', max: 100 },
            { text: '拍照', max: 100 },
            { text: '系统', max: 100 },
            { text: '性能', max: 100 },
            { text: '屏幕', max: 100 },
          ],
          valueList: [
            //纵轴数据
            {
              //每一项是每条线的数据
              name: '邮件营销', //右上角tooltip展示和每条线鼠标悬浮展示字
              data: [10, 32, 55, 12, 41],
              unit: '个',
              totalScore: '87.34', //总评分
            },
            {
              name: '联盟广告',
              data: [90, 10, 32, 14, 55],
              unit: '个',
              totalScore: '87.34', //总评分
            },
          ],
        }
        parseData(data)
        if (callback) {
          callback()
        }
      } else {
        nt.doRequest({
          method: 'post',
          uri: '/paas/chart-layout/v1/compdsconfig/testCompDSConfig',
          data: parseApi({
            api: this.api,
            time: this.time,
            mixinParam: this.mixinParam,
          }),
          onSuccess: (resp) => {
            let data = resp.data.content.content

            parseData(data)
            if (callback) {
              callback()
            }
          },
          onError: () => {
            parseData({})
            if (callback) {
              callback()
            }
          },
        })
      }
    },
    changeParam() {
      if (this.api) {
        this.getCommonData(this.changeStyle)
        clearInterval(this.comInterval)
        if (this.interval) {
          this.comInterval = setInterval(() => {
            this.getCommonData(this.changeStyle)
          }, this.interval * 1000)
        }
      }
    },
  },
  watch: {
    'api.dsName': function () {
      this.getCommonData(this.changeStyle, true)
    },
    componentData() {
      this.changeStyle()
    },
    changeSize() {
      this.$refs.radarChart.resize()
    },
    time() {
      this.changeParam()
    },
    mixinParam: {
      handler: function (val, oldVal) {
        let int = 0
        int = setInterval(() => {
          if (!this.chartLoading) {
            clearInterval(int)
            this.changeParam()
          }
        }, 50)
      },
      deep: true,
    },
  },
  mounted: function () {
    this.getCommonData(this.changeStyle)
    if (this.interval) {
      this.comInterval = setInterval(() => {
        this.getCommonData(this.changeStyle)
      }, this.interval * 1000)
    }
  },
  beforeDestroy() {
    clearInterval(this.comInterval)
  },
  emits: ['dataReady'],
}
</script>

<style scoped>
.pie-row {
  width: 100%;
  height: 100%;
}
</style>
